package club.xinghe.servlet.student;

import club.xinghe.biz.ExamBiz;
import club.xinghe.biz.ScoreBiz;
import club.xinghe.entity.Exam;
import club.xinghe.entity.Score;
import club.xinghe.entity.Student;
import club.xinghe.util.DateUtil;
import club.xinghe.util.JsonServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * 说明:学生登录成功后success.html进行异步加载数据的servlet
 *
 * @姚文斌
 * @create 2019-10-08 下午 5:12
 */
@WebServlet("/student/SuccessServlet")//注意修改路径
public class SuccessServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //写业务处理代码
        //得到当前时间
        Date date=new Date();
        String time= DateUtil.dateToString(date);
//        System.out.println(time);//输出当前时间
        //查看涉及该学生试卷,从域里面取值
            HttpSession session= request.getSession();
            Student student= (Student) session.getAttribute("student");
            //得到该学生的专业id和年级id
            int zid=student.getZy().getzId();
            int gid=student.getGid();
            //由专业id和年级id去查询试卷
            ExamBiz examBiz=new ExamBiz();
            List<Exam> list=examBiz.getExamByZidGid(gid,zid);
            List<Exam> examList=new ArrayList<>();
            for (Exam exam: list) {
                //得到考试卷子的起始和终止时间
                String start=exam.geteStart();
                String end=exam.geteEnd();

                //用工具类，看登录时间是否在这个区间里
                if (DateUtil.compareDate(start,time)&&DateUtil.compareDate(time,end)){
                    int eid=exam.geteId();//得到卷子ID
                    ScoreBiz scoreBiz=new ScoreBiz();
                    Score  score=scoreBiz.getScoreBySidEid(student.getsId(),eid);
                    //如果该生没有这个试卷的成绩,说明他在合法时间里区间还没考过此试卷,那么允许他看到此试卷;否则不给他看
                    if (score==null){
                        examList.add(exam);
                    }

                }
            }
        //返回给回调函数符合该生的专业和年级以及符合考试时间的试卷
        Map<String,Object>map=new HashMap<>();
            map.put("examList",examList);
            map.put("student",student);

        JsonServlet.getJson(request,response,map);
        System.out.println("已经调出该生的试卷-----By:SuccessServlet");


    }
}

